from selenium import webdriver
from time import sleep
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


class BasePage:

    def __init__(self, driver):

        # global driver
        # self.driver = webdriver.Chrome()
        self.driver = driver
        # self.driver.get("https://gj.kdzwy.com/index_new.html")
        # self.driver.implicitly_wait(8)
    """打开网页"""
    def go_to_url(self, url):
        self.driver.get(url)

    """定位关键元素并返回"""
    def locate_element(self, loc):
        return self.driver.find_element(*loc)

    """显式等待后定位关键元素并返回"""
    def wait_locate_element(self, loc):
        element = WebDriverWait(self.driver, 10, 0.5).until(EC.presence_of_element_located(loc))
        return element

    """设置关键字的值"""
    def send_keys(self, loc, value):
        self.wait_locate_element(loc).send_keys(value)

    """清空输入框后录入内容并点击ENTER"""
    def send_keys_enter(self, loc, value):
        from selenium.webdriver.common.keys import Keys
        element = self.wait_locate_element(loc)
        # element.clear()
        # sleep(0.5)
        element.send_keys(value)
        sleep(1)
        element.send_keys(Keys.ENTER)
        sleep(3)

    """点击关键字"""
    def click(self, loc):
        self.wait_locate_element(loc).click()

    """移动鼠标"""
    def move(self, loc):
        from selenium.webdriver.common.action_chains import ActionChains
        ac = ActionChains(self.driver)
        ac.move_to_element(
            self.wait_locate_element(loc)
        ).perform()

    """移动鼠标并点击"""
    def move_click(self, loc):
        element = self.wait_locate_element(loc)
        webdriver.ActionChains(self.driver).move_to_element(element).click(element).perform()

    """跳转iframe"""
    def switch_to_frame(self, loc):
        self.driver.switch_to.frame(self.wait_locate_element(loc))

    """退出所有的iframe"""
    def switch_to_default_content(self):
        self.driver.switch_to.default_content()

    """获取关键字文本值"""
    def get_value(self, loc):
        return self.wait_locate_element(loc).text

    """获取当前网页句柄"""
    def current_window(self):
        return self.driver.current_window_handle

    """跳转目标网页"""
    def switch_to_window(self, title):
        for handle in self.driver.window_handles:
            self.driver.switch_to.window(handle)
            if title in self.driver.title:
                break
        sleep(5)

    """返回主页面"""
    def switch_to_current_window(self, current_window):
        self.driver.switch_to.window(current_window)
